package com.mall.auth.service.impl;

import com.mall.common.entity.User;
import com.mall.common.result.Result;
import com.mall.system.feign.UserServiceFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户详情服务实现类
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserServiceFeignClient userServiceFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            // 通过Feign调用system服务获取用户信息
            Result<User> result = userServiceFeignClient.getUserByUsername(username);
            if (!result.getCode().equals(200) || result.getData() == null) {
                throw new UsernameNotFoundException("用户不存在");
            }

            User user = result.getData();
            if (user.getStatus() == 0) {
                throw new UsernameNotFoundException("账号已被禁用");
            }

            // 返回Spring Security用户对象
            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    AuthorityUtils.createAuthorityList("ROLE_USER")
            );
        } catch (Exception e) {
            log.error("加载用户详情异常: ", e);
            throw new UsernameNotFoundException("加载用户详情异常", e);
        }
    }
}